package service;

import dao.ITicketDao;
import dao.TicketDaoImpl;
import entity.Ticket;
import util.DateUtil;

import java.util.Date;
import java.util.List;

public class TicketServiceImpl implements ITicketService {
    private ITicketDao ticketDao = new TicketDaoImpl();

    @Override
    public boolean sellTicket(Ticket ticket) {
        for (Ticket t : ticketDao.getTicketsByScheduleId(ticket.getSchedule().getScheduleId())) {
            if (t.getSeatRow().equals(ticket.getSeatRow()) &&
                    t.getSeatNumber() == ticket.getSeatNumber() &&
                    t.getStatus().equals("已售出")) {
                return false;
            }
        }
        ticket.setStatus("已售出");
        return ticketDao.sellTicket(ticket);
    }

    @Override
    public boolean refundTicket(String electronicTicketId) {
        Ticket ticket = ticketDao.getTicketByElectronicId(electronicTicketId);
        if (ticket != null && ticket.getStatus().equals("已售出")) {
            Date now = new Date();
            long diffInMinutes = DateUtil.getTimeDifferenceInMinutes(now, ticket.getSchedule().getStartTime());
            if (diffInMinutes >= 60) {
                ticket.setStatus("未售出");
                return ticketDao.sellTicket(ticket);
            }
        }
        return false;
    }

    @Override
    public Ticket getTicketByElectronicId(String electronicTicketId) {
        return ticketDao.getTicketByElectronicId(electronicTicketId);
    }

    @Override
    public List<Ticket> getTicketsByScheduleId(String scheduleId) {
        return ticketDao.getTicketsByScheduleId(scheduleId);
    }

    @Override
    public List<Ticket> getTicketsByDate(Date date) {
        return null;
    }

    @Override
    public List<Ticket> getTicketsByMovieId(String movieId) {
        return null;
    }
}